<template>
  <div class="app-container app-container-next">
    <el-card class="box-card" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'coupon-codes-list'}">
          <el-button :round="true" icon="el-icon-back" plain size="small">
            返回
          </el-button>
        </router-link>
      </div>
      <el-row>
        <el-col :span="18">
          <el-form ref="submitForm" :model="mmsCouponCode" :rules="rules" label-width="120px">
            <h4>基本信息</h4>
            <el-form-item label="活动名称" prop="name">
              <el-input v-model="mmsCouponCode.name" placeholder="活动名称" maxlength="25" style="width: 440px"/>
            </el-form-item>
            <el-form-item label="折扣类型">
              <el-select v-model="mmsCouponCode.marketingType" placeholder="请选择" style="width: 440px">
                <el-option
                    v-for="item in marketingTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优惠门槛" prop="consumeMoney">
              <el-input v-model="mmsCouponCode.consumeMoney" placeholder="优惠门槛" style="width: 440px"
                        onKeyPress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false">
                <template slot="append">{{currencyType}}</template>
              </el-input>
            </el-form-item>
            <el-form-item :label="mmsCouponCode.marketingType=='reduction'?'满减金额':'折扣（1-99）'" prop="reduction" >
              <el-input v-model="mmsCouponCode.reduction"
                        :placeholder="mmsCouponCode.marketingType=='reduction'?'满减金额':'折扣（1-99）'"
                        onKeyPress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false" style="width: 440px">
                <template slot="append">{{mmsCouponCode.marketingType === 'reduction' ? currencyType + ' OFF' : '% OFF'}}
                </template>
              </el-input>
            </el-form-item>

            <h4>使用规则</h4>
            <el-form-item label="活动时间" prop="startDate" class="hasWidth">
              <el-date-picker
                  style="width: 210px"
                  v-model="mmsCouponCode.startDate"
                  type="datetime"
                  placeholder="开始日期"
                  align="right">
              </el-date-picker>
              <span>--</span>
              <el-date-picker
                  style="width: 210px"
                  v-model="mmsCouponCode.endDate"
                  type="datetime"
                  placeholder="结束日期"
                  align="right" :disabled="endDateCheck">
              </el-date-picker>
              <el-checkbox v-model="endDateCheck">不限制</el-checkbox>
            </el-form-item>
            <el-form-item label="优惠码" prop="couponCode" class="hasWidth">
              <el-input v-model="mmsCouponCode.couponCode" placeholder="优惠码" style="width: 296px"/>
              <el-button :loading="getStringRandomCodeLoading" @click="getStringRandomCode">自动生成优惠码</el-button>
            </el-form-item>
            <el-form-item label="总数量" prop="joinCount" class="hasWidth">
              <el-input v-model="mmsCouponCode.joinCount" placeholder="数量" style="width: 440px"
                        :disabled="joinCountCheck"
                        onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"/>
              <el-checkbox v-model="joinCountCheck">不限制</el-checkbox>
            </el-form-item>
            <el-form-item label="叠加优惠:">
              <el-switch
                  v-model="mmsCouponCode.superpositionFlag"
                  style="margin-left:10px">
              </el-switch>
              <span style="color: #f50606"><span style="color: #757c84">开启按钮可与满减活动叠加使用</span>（请谨慎开启）</span>
            </el-form-item>
            <h4>活动展示 <el-checkbox v-model="mmsCouponCode.isCreateActivityView">创建公告栏</el-checkbox></h4>
            <el-form-item>
              <el-button :loading="submitLoading" type="primary" @click="saveData('submitForm')">保存</el-button>
              <el-button @click="handleReset('coupon-codes-list')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
import {getStringRandomCode, addCouponCode} from '@/api/coupon-code';
import {mapGetters} from 'vuex';

export default {
    name: 'coupon-codes-add',
    data: function () {
        return {
            marketingTypeOptions: [{
                value: 'reduction',
                label: '满减优惠码'
            }, {
                value: 'discount',
                label: '折扣优惠码'
            }],
            mmsCouponCode: {
                name: '',
                consumeMoney: '',
                reduction: '',
                tradeTime: '',
                beginDate: '',
                endDate: '',
                couponCode: '',
                joinCount: '',
                limitCount: '',
                isCreateActivityView: false,
                superpositionFlag: false,
                startDate: '',
                marketingType: 'reduction'
            },
            joinCountCheck: true,
            limitCountChecked: true,
            endDateCheck: true,
            rules: {
                name: [
                    {required: true, message: '请填写活动名称', trigger: 'blur'}
                ],
                consumeMoney: [
                    {required: true, message: '请填写优惠门槛', trigger: 'blur'}
                ],
                reduction: [
                    {required: true, message: '请填写优惠力度', trigger: 'blur'}
                ],
                startDate: [
                    {required: true, message: '请选择开始时间', trigger: 'blur'}
                ],
                couponCode: [
                    {required: true, message: '请填写优惠码', trigger: 'blur'}
                ]
            },
            submitLoading: false,
            getStringRandomCodeLoading: false
        };
    },
    methods: {
        numCheck (value) {
            console.info('check');
            if (value.length === 1) {
                value = value.replace(/[^0-9]/g, '');
            } else {
                value = value.replace(/\D/g, '');
            }
        },
        getStringRandomCode () {
            this.getStringRandomCodeLoading = true;
            getStringRandomCode().then(res => {
                if (res.code === '200') {
                    this.getStringRandomCodeLoading = false;
                    this.mmsCouponCode.couponCode = res.data;
                }
            }).catch(() => {
                this.getStringRandomCodeLoading = false;
            });
        },
        handleReset (name) {
            this.$router.push({name: name});
        },
        saveData (formName) {
            this.mmsCouponCode.siteId = this.siteId;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    if (this.mmsCouponCode.startDate) {
                        this.mmsCouponCode.beginDate = new Date(this.mmsCouponCode.startDate + ' UTC' + this.timeZone).getTime();
                    }
                    if (this.mmsCouponCode.endDate) {
                        this.mmsCouponCode.endDate = new Date(this.mmsCouponCode.endDate + ' UTC' + this.timeZone).getTime();
                    }
                    if (this.endDateCheck) {
                        this.mmsCouponCode.endDate = undefined;
                    } else {
                        if (this.mmsCouponCode.beginDate >= this.mmsCouponCode.endDate) {
                            this.$message.error('开始时间必须在结束时间之前');
                            this.submitLoading = false;
                            return;
                        }
                    }
                    if (this.joinCountCheck) {
                        this.mmsCouponCode.joinCount = undefined;
                    }
                    if (this.limitCountChecked) {
                        this.mmsCouponCode.limitCount = undefined;
                    }
                    let mmsCouponCodeForSave = JSON.parse(JSON.stringify(this.mmsCouponCode));
                    mmsCouponCodeForSave.consumeMoney = Math.round(mmsCouponCodeForSave.consumeMoney * 100);
                    if (this.mmsCouponCode.marketingType === 'discount') {
                        if (this.mmsCouponCode.reduction % 1 !== 0 || this.mmsCouponCode.reduction < 1 || this.mmsCouponCode.reduction > 99) {
                            this.$message.error('折扣必须取1-99之间整数');
                            this.submitLoading = false;
                            return;
                        }
                    } else {
                        if (parseFloat(this.mmsCouponCode.reduction) >= parseFloat(this.mmsCouponCode.consumeMoney)) {
                            this.$message.error('满减金额应小于优惠门槛');
                            this.submitLoading = false;
                            return;
                        }
                        mmsCouponCodeForSave.reduction = Math.round(mmsCouponCodeForSave.reduction * 100);
                    }
                    addCouponCode(mmsCouponCodeForSave).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('新增成功');
                            this.handleReset('coupon-codes-list');
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        }
    },
    computed: {
        ...mapGetters(['timeZone', 'siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencyType () {
            return this.siteInfo.currencyType;
        }
    }
};

</script>

<style scoped>

</style>
